<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


class Saoyisao extends CI_Controller{
    private $appId;
    private $appSecret;
    
    function __construct() {
        parent::__construct();
        $this->appId = "wx48ac7010d65a20d7";
        $this->appSecret = "yWmfWG4nIkjatVdWuWdgqEk1NhjipzzTW6xHVhODYe2FdE6Q3XkoY2aEy53ShZCi";
        $this->load->library('Saoyisao');
    }
    public function index() {
        $this->load->library('Saoyisao');
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		//$url = $_SERVER[HTTP_REFERER];
		//var_dump($url);
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        var_dump($signPackage);
        $this->load->view("Saoyisao",$signPackage);
    }

  private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
  }

  private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode(file_get_contents("weixinJS/jsapi_ticket.json"));
        $data = $this->Data_model->get_single_data(array('type' => 'jsapi_ticket'),"WEIXININFO");
        if ($data['time'] < time()) {
            $accessToken = $this->get_access_token();
            // 如果是企业号用以下 URL 获取 ticket
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            //$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->http_request_json($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $this->Data_model->update_data(array('type' => 'jsapi_ticket'),array('time' => time() + 7000,'jsapi_ticket' => $ticket),"WEIXININFO");
                /*
                        $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("weixinJS/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
                 * 
                 */
            }
        } else {
            $ticket = $data['jsapi_ticket'];
        }
        return $ticket;
  }

  /*
    public  function index($userid){
        header("Access-Control-Allow-Origin:*");
        $this->load->library('SalaryInfo');
        $one_date = date("Ym",strtotime("-1 month"));
        $two_date = date("Ym",strtotime("-2 month"));
        $three_date = date("Ym",strtotime("-3 month"));
        $four_date = date("Ym",strtotime("-4 month"));
        $five_date = date("Ym",strtotime("-5 month"));
        $res_dataone = $this->Data_model->get_single_data("GZ_YM = '".$one_date."' and A0190 = '".$userid."'","C21POOL");
        $res_datatwo = $this->Data_model->get_single_data("GZ_YM = '".$two_date."' and A0190 = '".$userid."'","C21POOL");
        $res_datathree = $this->Data_model->get_single_data("GZ_YM = '".$three_date."' and A0190 = '".$userid."'","C21POOL");
        $res_datafour = $this->Data_model->get_single_data("GZ_YM = '".$four_date."' and A0190 = '".$userid."'","C21POOL");
        $res_datafive = $this->Data_model->get_single_data("GZ_YM = '".$five_date."' and A0190 = '".$userid."'","C21POOL");
        
        $res_dataone['href'] = "collapseOne";
        $res_datatwo["href"] = "collapseTwo";
        $res_datathree["href"] = "collapseThree";
        $res_datafour["href"] = "collapseFour";
        $res_datafive["href"] = "collapseFive";
        $res_dataone['date_show'] = $one_date;
        $res_datatwo["date_show"] = $two_date;
        $res_datathree["date_show"] = $three_date;
        $res_datafour["date_show"] = $four_date;
        $res_datafive["date_show"] = $five_date;
        $result_data = array(
            "data" => array(
                "1" => $res_dataone,
                "2" => $res_datatwo,
                "3" => $res_datathree,
                "4" => $res_datafour,
                "5" => $res_datafive
            )
        );
        $this->load->view("SalaryInfo",$result_data);
        //$this->load->view("SalaryInfo",$res);
    }
   * 
   */
    public function getOauth2(){
        if (isset($_GET['code'])){
            $code = $_GET['code'];
            $res = $this->Data_model->get_single_data(array('name'=>'中兴精密',
                                                            'type'=>'Check_47'),"WEIXININFO");
            $this->get_userId($res['access_token'], $code,$res['agentid']);
        }else{
            echo "NO CODE";
        }
    }
    
    function get_userId($access_token,$code,$agentId){
        if($access_token){
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code."&agentid=".$agentId;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['errcode'])){
                if($data['errcode'] == "40001" or $data['errcode'] == '42001' or $data['errcode'] == '40014'){
                    $this->get_access_token();
                    
                    /*
                    $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code."&agentid=".$agentId;
					$json=self::http_request_json($url);//这个地方不能用file_get_contents
					$data=json_decode($json,true);
					$this->index($data['UserId']);
                     
                     * 
                     */
                    
                    $newurl = "<?=base_url()?>/SalaryInfo/getOauth2?code=".$code;
                    echo "<script language='javascript' type='text/javascript'>";  
                    echo "window.location.href='".$newurl."'";  
                    echo "</script>"; 
                    
                }else{
                    echo "页面请求错误，请检查！";
                }
            }else{
                $this->index($data['UserId']);
            }
        }else{
            $this->get_access_token();
            $this->getOauth2();
        }
    }
    function get_access_token(){
        $result = $this->Data_model->get_single_data(array('name'=>'中兴精密',
                                                            'type'=>'Check_47'),"WEIXININFO");
        if($result['time'] < time()){
            $corpid = $result['corpid'];
            $corpsecret = $result['corpsecret'];
            $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['access_token'])){
                $this->Data_model->update_data(array('name'=>'中兴精密',
                                                                'type'=>'Check_47'),array('access_token' => $data['access_token'],'time' => time()+7100),'WEIXININFO');
            
                $access_token = $data['access_token'];
            }else{
                return "获取access_token错误";
            } 
        }else{
            $access_token = $result['access_token'];
        }
        return $access_token;
        
               
    }
    /*
    function get_access_token(){
        $result = $this->Data_model->get_single_data(array('name'=>'中兴精密',
                                                            'type'=>'Check_47'),"WEIXININFO");
        $corpid = $result['corpid'];
        $corpsecret = $result['corpsecret'];
        $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
        $json=self::http_request_json($url);//这个地方不能用file_get_contents
        $data=json_decode($json,true);
        if(isset($data['access_token'])){
            $this->Data_model->update_data(array('name'=>'中兴精密',
                                                            'type'=>'Check_47'),array('access_token' => $data['access_token']),'WEIXININFO');
        }else{
            return "获取access_token错误";
        }        
    }
     * 
     */
    //因为url是https 所有请求不能用file_get_contents,用curl请求json 数据
    function http_request_json($url){  
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;  
    }
    
    function downloadfile(){
        $mediaid = $_REQUEST['mediaid'];
        $this->Data_model->update_data(array('id' => '4'),array('jsapi_ticket' => $mediaid),'WEIXININFO');
        $access_token = $this->get_access_token();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$mediaid;
        $fileInfo = $this->downloadWeixinFile($url);
	    $savePath = "html/image/";
        $filename = $savePath.date("Ymd",  time())."_".$mediaid.".jpg";
        $this->saveWeixinFile($filename, $fileInfo["body"]);
        echo $filename;
    }
    function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package)); 
        return $imageAll;
    }
 
    function saveWeixinFile($filename, $filecontent)
    {
        $local_file = fopen($filename, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file, $filecontent)) {
                fclose($local_file);
            }
        }
    }
} 
